/* 
 * @author 百無禁忌
 * @date 2021-02-26 09:20
 * 参考 gitee // https://gitee.com/myDarling/uniapp-extend
 * socketOpen: 监听 WebSocket 是否打开 默认false
 * socketTask: 创建 WebSocket 实例
 */
let [socketOpen,socketTask]=[false];
const api = [
	{url: 'ws://190.168.1.57:8082'}
]
const index=0;  //0开发 1测试 2正式
const url = api[index].url;

/* 
 p: Obj
 p:{
	 url: '', 
	 mid: '',
	 token: '',
	 from: '',
	 channel: 3
 }
 */
let initSocket = p =>{
	socketTask = uni.connectSocket({
		url,
		header: {
			"mid": p.mid,
			"token": p.token,
			"from": "BUSINESS",
			"channel": 3
		},
		success:(res)=>{
			// console.log(res,'方法成功')
		}
	})
	
	console.log(socketTask,'创建 WebSocket 实例 ')
	
	/* WebSocket 已连接 */
	socketTask.onOpen(res => {
		console.log('WebSocket 连接已打开');
		socketOpen=true;
	})
	
	/* WebSocket 连接失败 */
	socketTask.onError(res => {
		console.log('WebSocket 连接失败');
	});
	
	/* 接收服务器返回的数据 */
	socketTask.onMessage(res => {
		uni.$emit('dataSocket',res.data)
	})
}

/* 启动 */
let start = (p) => { 
	if(socketOpen){
		console.log("不能重复打开连接")
		return;
	}
	initSocket(p)
}
/* 关闭 */
let closeSocket = () => {
	socketTask.close({
		code: 1000,
		reason: '手动关闭',
		success:()=>{
			console.log("WebSocket 连接已关闭")
			socketOpen=false
		}
	})
}

/* 发送数据 */
let send = (value) => {
	if(!socketOpen){
		console.log('连接未打开')
		return
	}
	
	uni.sendSocketMessage({ data:value })
}

/* 接收数据 */
let data=(callback)=>{
	uni.$on("dataSocket",(res)=>{
		callback && callback(res)
	})
}

export default {
	start,
	closeSocket,
	send,
	data
}
